<?php
/**
 * Created by cmb_weixin.master.
 * File: Product.php
 * User: xuewl
 * Date: 2017/12/14
 * Time: 02:51
 */
namespace app\api\controller\v1\product;
use app\api\controller\v1\Init;

class Product extends Init
{

    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('product/product', 'service');
    }

    public function items() {
        extract($this->params, true);
        $maps = [
            'status' => 1
        ];
        $order = $this->params['order'] ?: 'sort ASC';
        $extra = $this->params['extra'] && !is_array($this->params['extra']) ? explode(",", $this->params['extra']) : [];
        $attrs = $this->params['attrs'] && !is_array($this->params['attrs']) ? explode(",", $this->params['attrs']) : [];

        $result = $this->model->lists($maps, $this->limit, $this->page, $order, true, $extra, [], $attrs);
        return $this->response(lang('Operation completed'), $result);
    }

    public function item() {
        $result = $this->model->where([
            'id' => $this->params['id'],
            'status' => 1,
        ])->find();

        if(!$result) {
            return $this->response('产品不存在', [], -20002);
        }

        if($this->params['attrs']) {
            $attrs = explode(",",$this->params['attrs']);
            array_map(function($attr) use (&$result) {
                $attr = trim($attr);
                return $result->$attr = $result->getAttr($attr);
            }, $attrs);
        }

        return $this->response('产品获取成功', $result);
    }

}